<template>
  <div>
    <el-divider content-position="left">角色授权</el-divider>
    <div>
      <div>
        <el-transfer
          v-model="value"
          filterable
          :titles="['初始角色', '赋予角色']"
          @change="handleChange"
          :data="data">
          <span slot-scope="{ option }">{{ option.label }}</span>
        </el-transfer>
        <el-form :inline="true">
          <el-form-item label="选择用户">
            <el-select v-model="userId" @change="getRoleList(userId)" clearable>
              <el-option
                v-for="item in userData"
                :key="item.id"
                :label="item.userName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addRole">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
  import {addRole, getRoleByUserId} from "@/api/role";
  import {getUserList} from '@/api/user'

  export default {
    name: "addRoleManage",
    mounted() {
      getUserList().then((r) => {
        console.log(r)
        this.userData = r
      })
    },
    data() {
      return {
        data: [
          {
            key: 'admin',
            label: '管理员'
          }, {
            key: 'user',
            label: '普通用户'
          }
        ],
        value: [],
        userId: '',
        userData: []
      }
    },
    methods: {
      getRoleList(userId) {
        if (!userId) {
          return
        }
        this.value = [];
        getRoleByUserId(userId).then((r) => {
          this.value = r;
        })
      },
      handleChange(value, direction, movedKeys) {
      },
      addRole() {
        if (this.userId == '') {
          this.$message.error('请选择用户');
          return
        }
        var roleList = this.value.join(",");
        addRole({
          "roleCodeList": roleList,
          "userId": this.userId
        }).then((r) => {
          this.$message.success('操作成功')
        })
      }
    }
  }
</script>

<style scoped>

</style>
